package com.runvp.netty.server;

import com.runvp.common.config.NettyConfig;
import com.runvp.netty.impl.NettyChannelInitializerImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * *
 * NettyBufServer 初始化Server
 *
 * @author xkk
 * @Date 2020/07/13 07:13
 **/
@Component
@Slf4j
public class NettyBufServer {
    @Autowired
    private NettyChannelInitializerImpl nettyChannelInitializer;


    public void bind() throws Exception {
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            log.info("Netty服务启动中 ..." );
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(nettyChannelInitializer);
            //接受socket缓冲区大小 等同于 滑动窗口的初始值 65535
            b.option(ChannelOption.SO_RCVBUF, 1024*1024);
            //netty创建ByteBuf时 执行大小 默认1024 child ScoketChannel相关
            b.childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(1024, 20480, 65536));
            // 绑定端口，同步等待成功
            ChannelFuture f = b.bind(NettyConfig.getIntPort()).sync();
            log.info("Netty服务启动成功,端口: " + NettyConfig.getIntPort());
            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
